﻿using MES.Server.Common.Jwt;
using MES.Server.Entities;
using MES.Server.EntitiesDTO;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MES.Server.AuthServer.Utility.JwtService
{
    /// <summary>
    /// 对称可逆加密实现
    /// </summary>
    public class CustomHSJWTService : CustomJWTService
    {
        private readonly JWTTokenOptions _JWTTokenOptions;
        public CustomHSJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
        {
            if (jwtTokenOptions.CurrentValue == null)
            {
                throw new Exception("没有配置Jwt 秘钥~");
            }
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
        }

        /// <summary>
        /// 对称可逆加密生成Token
        /// </summary>
        /// <param name="user"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public override string CreateToken(UserEntity user, out string refreshToken)
        {
            //准备有效载荷
            List<Claim> claimsArray = base.UserToClaim(user);
            //准备加密key
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecurityKey!));

            //Sha256 加密方式
            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


            JwtSecurityToken JwtAccessToken = new JwtSecurityToken(
                  issuer: _JWTTokenOptions.Issuer,
                  audience: _JWTTokenOptions.Audience,
                  claims: claimsArray.ToArray(),
                  expires: DateTime.Now.AddMinutes(5),//5分钟有效期
                  signingCredentials: creds);
            string accesstoken = new JwtSecurityTokenHandler().WriteToken(JwtAccessToken);
            refreshToken = "";
            return accesstoken;
        }
    }
}
